from tkinter import *
# from tkinter.messagebox import *
from tkinter import messagebox, filedialog
import base64
import re
import tkinterweb

import requests


class LoginPage(object):
    def __init__(self, master=None):
        self.root = master  # 定义内部变量root
        self.root.geometry('%dx%d' % (300, 180))  # 设置窗口大小
        self.username = StringVar()
        self.username.set("zhubin")
        self.password = StringVar()
        self.password.set("546888")
        self.createPage()

    def createPage(self):
        self.page = Frame(self.root)  # 创建Frame
        self.page.pack()
        Label(self.page).grid(row=0, stick=W)
        Label(self.page, text='账户: ').grid(row=1, stick=W, pady=10)
        Entry(self.page, textvariable=self.username).grid(row=1, column=1, stick=E)
        Label(self.page, text='密码: ').grid(row=2, stick=W, pady=10)
        Entry(self.page, textvariable=self.password, show='*').grid(row=2, column=1, stick=E)
        Button(self.page, text='登陆', command=self.loginCheck).grid(row=3, stick=W, pady=10)
        Button(self.page, text='退出', command=self.page.quit).grid(row=3, column=1, stick=E)

    def loginCheck(self):
        name = self.username.get()
        secret = self.password.get()
        if name == 'zhubin' and secret == '546888':
            self.page.destroy()
            MainPage(self.root)
        else:
            messagebox.showinfo(title='错误', message='账号或密码错误！')


class MainPage(object):
    def __init__(self, master=None):
        self.root = master  # 定义内部变量root
        self.root.geometry('%dx%d' % (600, 400))  # 设置窗口大小
        self.createPage()

    def createPage(self):
        self.inputPage = InputFrame(self.root)  # 创建不同Frame
        self.queryPage = QueryFrame(self.root)
        self.countPage = CountFrame(self.root)
        self.aboutPage = AboutFrame(self.root)
        self.inputPage.pack()  # 默认显示数据录入界面
        menubar = Menu(self.root)
        menubar.add_command(label='数据录入', command=self.inputData)
        menubar.add_command(label='查询', command=self.queryData)
        menubar.add_command(label='统计', command=self.countData)
        menubar.add_command(label='关于', command=self.aboutDisp)
        self.root['menu'] = menubar  # 设置菜单栏

    def inputData(self):
        self.inputPage.pack()
        self.queryPage.pack_forget()
        self.countPage.place_forget()
        self.aboutPage.pack_forget()

    def queryData(self):
        self.inputPage.pack_forget()
        self.queryPage.pack()
        self.countPage.place_forget()
        self.aboutPage.pack_forget()

    def countData(self):
        self.inputPage.pack_forget()
        self.queryPage.pack_forget()
        self.countPage.place(relx=0,rely=0,width=580, height=400)
        self.aboutPage.pack_forget()

    def aboutDisp(self):
        self.inputPage.pack_forget()
        self.queryPage.pack_forget()
        self.countPage.place_forget()
        self.aboutPage.pack()


class InputFrame(Frame):  # 继承Frame类
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.root = master  # 定义内部变量root
        self.itemName = StringVar()
        self.importPrice = StringVar()
        self.sellPrice = StringVar()
        self.deductPrice = StringVar()
        self.createPage()

    def createPage(self):
        Label(self).grid(row=0, stick=W, pady=10)
        Label(self, text='昵称: ').grid(row=1, stick=W, pady=10)
        Entry(self, textvariable=self.itemName).grid(row=1, column=1, stick=E)
        Label(self, text='性别: ').grid(row=2, stick=W, pady=10)
        Entry(self, textvariable=self.importPrice).grid(row=2, column=1, stick=E)
        Label(self, text='绑定手机号: ').grid(row=3, stick=W, pady=10)
        Entry(self, textvariable=self.sellPrice).grid(row=3, column=1, stick=E)
        Label(self, text='绑定邮箱: ').grid(row=4, stick=W, pady=10)
        Entry(self, textvariable=self.deductPrice).grid(row=4, column=1, stick=E)
        Button(self, text='录入').grid(row=6, column=1, stick=E, pady=10)


class QueryFrame(Frame):  # 继承Frame类
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.root = master  # 定义内部变量root
        self.itemName = StringVar()
        self.createPage()

    def createPage(self):
        Label(self, text='查询界面').grid(row=0, column=0)
        self.text1 = Text(self, width=40, height=10, bg="gray")
        self.text1.grid(row=1, column=0, columnspan=2, sticky=EW)
        self.btn01 = Button(self, text="Base64解码(Decode)", command=self.b64decode)
        self.btn01.grid(row=1, column=2)
        self.text2 = Text(self, width=40, height=10, bg="gray")
        self.text2.grid(row=2, column=0, columnspan=2, sticky=EW)
        self.btn02 = Button(self, text="Base64编码(Eecode)", command=self.b64encode)
        self.btn02.grid(row=2, column=2)

    def b64decode(self):
        try:
            text = self.text1.get(0.0, END)
            str_decode = base64.b64decode(text)
            str = str_decode.decode("utf-8")
            self.text2.delete(0.0, END)
            self.text2.insert(INSERT, str)
        except:
            messagebox.showerror("错误", "解码错误！")

    def b64encode(self):
        text = self.text2.get(0.0, END)
        b_text = text.encode("utf-8")
        str_decode = base64.b64encode(b_text)
        self.text1.delete(0.0, END)
        self.text1.insert(INSERT, str_decode)


class CountFrame(Canvas):  # 继承Frame类
    def __init__(self, master):
        Canvas.__init__(self, master)
        self.root = master  # 定义内部变量root
        self.createPage()

    def myfunction(self, event):
        self.configure(scrollregion=self.bbox("all"), width=100, height=400)

    def createPage(self):
        self.myscrollbar = Scrollbar(self.root, orient="vertical", command=self.yview)  # 创建滚动条
        self.myscrollbar.place(x=580, y=0, height=400)  # 滚动条定位，高度
        self.configure(yscrollcommand=self.myscrollbar.set)
        self.rollFrame = Frame(master=self)  # 在画布上创建frame
        self.rollFrame.pack(expand=1, fill=BOTH)  # self本身是一个组件，需要调用布局管理器
        self.create_window((0, 0), window=self.rollFrame, anchor="nw")  # 要用create_window才能跟随画布滚动
        self.rollFrame.bind("<Configure>", self.myfunction)

        Label(self.rollFrame, text='统计界面').grid(row=0, column=0)
        Label(self.rollFrame, text="搜索🔍: ").grid(row=1, column=0)
        # row--单元格行号 column--单元格列号
        self.v1 = StringVar()
        self.entry01 = Entry(self.rollFrame, textvariable=self.v1)
        self.entry01.grid(row=1, column=1)
        Label(self.rollFrame, text="图表来源: https://icon.macw.com/").grid(row=1, column=2)
        self.btn01 = Button(self.rollFrame, text=" 提取资源~", command=self.get_ico).grid(row=2,
                                                                                      column=0,
                                                                                      sticky=EW)  # sticky--组件紧贴所在单元格的某一角，对应于东南西北中以及4个角

    def get_ico(self):
        messagebox.showinfo("提示", "正在调用get_ico函数~")
        self.research = self.v1.get()
        print(self.research)
        url = f"https://icon.macw.com/search/{self.research}.html"
        headers = {
            "cookie": "PHPSESSID=2mlsi21tq7o7ih2i84a386fdnq",
            "referer": "https://icon.macw.com/pack/1352.html",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
        }
        response = requests.get(url, headers=headers).text
        url_list = []
        url_list_ = re.findall('''<div class="img"><img src="(.*?)" alt="(.*?)"></div>''', response, re.S)
        print(url_list_)
        for url in url_list_:
            url_list.append(url[0])
        try:
            for i in range(len(url_list)):
                Label(self.rollFrame, text=str(i + 1)).grid(row=i + 3, column=0)
                Button(self.rollFrame, text=url_list[i], command=lambda: self.download(url_list[i])).grid(row=i + 3,
                                                                                                          column=1,
                                                                                                          sticky=EW)
        except:
            messagebox.showerror("Error", "获取GIF资源失败！")

    def download(self, gif_url):
        filename = filedialog.asksaveasfilename(filetypes=[("PNG", ".png"), ("JPEG", ".jpeg"),
                                                           ("BMP", ".bmp"), ("JPG", ".jpg"),
                                                           ("GIF", ".gif"), ("python", ".py")])
        if filename:
            with open(file=filename, mode='wb') as f:
                content = requests.get(gif_url).content
                f.write(content)
                messagebox.showinfo("Downloading", "下载完成~")


class AboutFrame(Frame):  # 继承Frame类
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.root = master  # 定义内部变量root
        self.createPage()

    def createPage(self):
        Label(self, text='关于界面').grid(row=0,column=0)
        html_frame=tkinterweb.HtmlFrame(self)
        html_frame.grid(row=1,column=0)
        html_frame.load_website("index.html")



# 初始化窗口
root = Tk()
root.title('小程序')
LoginPage(root)
root.mainloop()
